const jwt = require('jsonwebtoken');
const secretKey = 'itheima No1 ^_^';

module.exports = class favoriteModel extends require('./Model') {
    // 添加收藏
    static addFavorite(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }
            try {
                const decoded = jwt.verify(token, secretKey);
                const userId = decoded.id;

                const { name, goodId, remark, coverImg } = req.body;
                if (!name || !goodId) {
                    return res.status(400).send({ status: 0, message: 'error', errorMessage: "缺少必要参数" });
                }

                let sql = 'INSERT INTO favorites (name, good_id, remark, cover_img, user_id, status) VALUES (?, ?, ?, ?, ?, 1)';
                this.query(sql, [name, goodId, remark, coverImg, userId])
                    .then((result) => {
                        if (result.affectedRows === 0) {
                            reject({ message: '收藏失败' });
                        } else {
                            resolve({ message: '收藏成功' });
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }

    // 删除收藏
    static deleteFavorite(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }
            try {
                const decoded = jwt.verify(token, secretKey);
                const userId = decoded.id;

                const { id } = req.body;
                if (!id) {
                    return res.status(400).send({ status: 0, message: 'error', errorMessage: "缺少必要参数" });
                }

                let sql = 'UPDATE favorites SET status = 0 WHERE user_id = ? AND id = ? AND status = 1';
                this.query(sql, [userId, id])
                    .then((result) => {
                        if (result.affectedRows === 0) {
                            reject({ message: '未找到相关收藏项' });
                        } else {
                            resolve({ message: '删除成功' });
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }

    // 获取用户收藏列表
    static getFavorites(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }

            try {
                const decoded = jwt.verify(token, secretKey);
                const userId = decoded.id;

                let sql = 'SELECT * FROM favorites WHERE user_id = ? AND status = 1';
                this.query(sql, [userId])
                    .then((result) => {
                        resolve(result);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }
}